import ReactDOM from 'react-dom'
import {Component} from 'react';
import {Input, Button, Tree} from 'antd';
import LimitSpan from '../../../component/LimitSpan';
import NoSelect from '../../../component/NoSelect';
import Icon from '../../../component/Icon';
import Affix from '../../../component/Affix';
import WangEditor from '../../../component/WangEditor';
import {resource} from '../../../config/config';
import {scrollTop, trimHtmlTag} from '../../../util/utils';
import {dispatch} from '../../../util/app';
import {Link} from 'dva/router';
import {connect} from 'dva';
import {getLoginSession} from '../../../plugin/loginSession';
import {htmlDecode} from '../../../util/utils';
import styles from './css/BlogDetail.css';

function offset(ele) {
    var top = ele.offsetTop;
    var left = ele.offsetLeft;
    while (ele.offsetParent) {
        ele = ele.offsetParent;
        if (window.navigator.userAgent.indexOf('MSTE 8') > -1) {
            top += ele.offsetTop;
            left += ele.offsetLeft;
        } else {
            top += ele.offsetTop + ele.clientTop;
            left += ele.offsetLeft + ele.clientLeft;
        }
    }
    return {
        left: left,
        top: top
    }

}
const TreeNode = Tree.TreeNode;
function renderTree(tree) {
	let nodes = [];
	let repeat = {};
	let i = 0;
	if (tree && tree.length > 0) {
		for (let item of tree) {
			let cNode = getTreeNode(item, i ++ + '', repeat);
			if (cNode)
				nodes.push(cNode);
		}
	}
	return nodes;
}
function getTreeNode(node, layer, repeat) {
	let nodes;
	if (node) {
		let cs = node.children;
		if (cs && cs.length > 0) {
			nodes = [];
			let i = 0;
			for (let item of cs) {
				nodes.push(getTreeNode(item, layer + '-' + (i ++), repeat));
			}
		}
		let count = repeat[node.name] || 0;
		repeat[node.name] = count + 1;
		return <TreeNode title={node.name} key={layer + '-' + count + '-' + node.name} >{nodes}</TreeNode>;
	}
}

class BlogDetail extends Component {
	
	constructor(...args) {
		super(...args);
		this.changeIsTop = this.changeIsTop.bind(this);
	}
	
	changeIsTop() {
		this.props.dispatch({type: 'blogDetail/changeIsTop', payload: scrollTop() == 0});
	}
	
	render() {
		let loginSession = getLoginSession();
		let {state: {currentBlog={}, blogEdit, isTop, isHtmlModel, catalog}, dispatch} = this.props;
		let opNode, editorMopdelNode, catalogNode;
		
		if (catalog && catalog.length > 0)
			catalogNode = (
				<Affix className={styles.catalog} offsetTop={120}>
					<NoSelect>
						<span className={styles.catalogTitle}>
							目录
						</span>
						<Tree onSelect={(selectedKeys, e) => {
							let finds;
							let offsetTop;
							if (scrollTop() == 0) 
								offsetTop = -104;
							else
								offsetTop = 0;
							if (blogEdit) {
								let find1 = document.querySelectorAll('.findDom1>div');
								find1 = find1[1];
								offsetTop += find1.offsetTop;
								find1 = find1.querySelector('div');
								if (find1) {
									offsetTop += find1.offsetTop;
									finds = find1.childNodes;
								}
							} else {
								let find2 = document.querySelector('.findDom2');
								if (find2)
									finds = find2.childNodes;
							}
							
							if (selectedKeys && selectedKeys.length > 0) {
								selectedKeys = selectedKeys[0];
								if (selectedKeys) {
									let tag;
									let ks = selectedKeys.split('-');
									if (ks && ks.length == 3)
										tag = 'h1';
									if (ks && ks.length == 4)
										tag = 'h2';
									let txt = ks[ks.length - 1];
									let repeat = ks[ks.length - 2];
									let count = 0;
									
									if (tag && finds && finds.length > 0) {
										for (let item of finds) {
											if (item.nodeName.toLowerCase() == tag) {
												let inner = item.innerHTML || item.innerText;
												inner = trimHtmlTag(inner);
												if (htmlDecode(inner) == htmlDecode(txt)) {
													if (count == repeat) {
														scrollTo(0, offsetTop + item.offsetTop);
														break;
													}
													count ++;
												}
											}
										}
									}
									
								}
							}
						}}>
							{renderTree(catalog)}
						</Tree>
					</NoSelect>
				</Affix>
			);
		if(loginSession) {
			if(blogEdit) {
				opNode = (
					<span className={styles.opLabel} onClick={() => {
						dispatch({type: 'blogDetail/changeBlogEdit', payload: false});
					}}>
						编辑模式
					</span>
				);
				editorMopdelNode = (
					<Affix className={styles.editorMopdelContainer} offsetTop={120}>
						<div>
							<Button className={styles.editorMopdelButton} type={isHtmlModel ? undefined : 'primary'} onClick={() => {
								dispatch({
					      			type: 'blogDetail/changeIsHtmlModel',
					      			isHtml: false
					      		})
							}}>
								富文本模式
							</Button>
						</div>
						<div>
							<Button className={styles.editorMopdelButton} type={isHtmlModel ? 'primary' : undefined} onClick={() => {
								dispatch({
					      			type: 'blogDetail/changeIsHtmlModel',
					      			isHtml: true
					      		})
							}}>
								HTML模式
							</Button>
						</div>
					</Affix>
				);
			} else {
				opNode = (
					<span className={styles.opLabel}  onClick={() => {
						dispatch({type: 'blogDetail/changeBlogEdit', payload: true});
						dispatch({type: 'blogDetail/changeIsHtmlModel', isHtml: false});
					}}>
						阅读模式
					</span>
				);
			}
		}
		
		return (
			<div className='blogDetailPageContainer'>
				<Affix onChange={this.changeIsTop}>
					<NoSelect>
						<div className={styles.head + (isTop ? ' ' + styles.bottomShadow : ' ')}>
							<Link to='/'>
								<Icon className={styles.backIcon} type={require('../../../asset/svg/backArrow.svg')} />
							</Link>
							<LimitSpan className={styles.title}>
								{currentBlog.title}
							</LimitSpan>
							{opNode}
						</div>
						<div className={styles.toolBarContainer + (!isTop ? ' ' + styles.bottomShadow : ' ')}>
							<div className={styles.toolBar + (blogEdit && !isHtmlModel ? '' : ' ' + styles.disabled)}>
								<div ref="toolbar"></div>
							</div>
						</div>
					</NoSelect>
				</Affix>
				<div className={styles.body}>
					<div className={styles.content}>
						{catalogNode}
						{editorMopdelNode}
						<div className={styles.contentTitleContainer}>
							<Input.TextArea className={styles.contentTitle} autosize={{minRows: 1}} value={currentBlog.title} disabled={!blogEdit} onChange={(e) => {
								dispatch({type: 'blogDetail/changeCurrentBlogTitle', payload: e.target.value});
							}} />
						</div>
						<div className={styles.contentBody}>
							<WangEditor 
								ref='editor' 
								readOnly={!blogEdit} 
								isHtml={isHtmlModel} 
								uploadImgServer={resource('/api/upload/files')} 
								onChange={(html) => {
									dispatch({type: 'blogDetail/changeCurrentBlogContent', payload: html});
								}} 
								onCatalogChange={tree => {
									dispatch({type: 'blogDetail/changeCatalog', catalog: tree});
								}}
								html={currentBlog.content} 
								menus={[
									'undo',// 撤销
								    'redo',// 重复
									'head',// 标题
								    'bold',// 粗体
								    'italic',// 斜体
								    'underline',// 下划线
								    'strikeThrough',// 删除线
								    'foreColor',// 文字颜色
								    'backColor',// 背景颜色
								    'link',// 插入链接
								    'list',// 列表
								    'justify',// 对齐方式
								    'table',// 表格
								    'image',// 插入图片
								    'video',// 插入视频
								    'quote',// 引用
								    'code',// 插入代码
								]}
							/>
						</div>
					</div>
				</div>
			</div>
		);
	}
	
	componentDidMount() {
		scrollTo(0, 0);
		this.changeIsTop();
		dispatch({
			type: 'blogDetail/init', 
			recordId: this.props.params.recordId,
			editorInit: defaultHtml => this.refs.editor.init({t: this.refs.toolbar}, defaultHtml)
		});
	}
	
}

export default connect((state) => ({
	state: {
		...state.blogDetail,
		loading: state.loading.models.blogDetail
	}
}))(BlogDetail);